#include <stdio.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <string.h>
#include <time.h>

#include "epoll.h"
#include "hash.h"
#include "String.h"

void test ()
{
    Ep *ep = ep_create (2048);
    Hash *phash = hash_create (10);
    int i;
    int n1 = 0, n2 = 0, n3 = 0, state = 0, rtime = 0;

    struct hostent *phost = gethostbyname("google.com");
    struct sockaddr_in serv_addr;

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(80);
    serv_addr.sin_addr = *((struct in_addr *)phost->h_addr);
    bzero(&(serv_addr.sin_zero), 8);

    for (i = 0; i < 2; i++) {
        int sock = hash_alloc (phash, "7pub.com", 0);
        ep_add (ep, sock, EPOLLIN|EPOLLOUT|EPOLLET);
    }

    for (i = 0; i < 50; i++) {
        int tt = time(NULL);
        int nfds = ep_wait (ep);

        tt = time(NULL)-tt;
        rtime += tt;
        if (tt > 0)
            state = -1;
        tt = 0;
        int j = 0;
        printf ("nfds: %d hashn: %d\n", nfds, phash->n);

        while (1) {
            int sock = hash_alloc (phash, "7pub.com", 0);
            if (sock > 0)
                ep_add (ep, sock, EPOLLIN|EPOLLOUT|EPOLLET);
            else break;
        }

        for (j = 0; j < nfds; j++) {
            int ev = ep->events[j].events;
            int so = ep->events[j].data.fd;

            printf ("%#x %d\n", ev, so);

            if (ev == 0x14) {
                int t = time(NULL);
                connect (so, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr));
                n1++;
                t = time(NULL)-t;
                if (t > 0)
                    state = ev;
            }
            else if (ev == 0x4) {
                int t = time(NULL);
                send (so, " \r\n\r\n", 5, 0);
                n2++;
                t = time(NULL)-t;
                if (t > 0)
                    state = ev;
            }
            else if (ev == 0x5) {
                int t = time(NULL);
                int recvbytes;
                char buf[1000];
                do {
                    recvbytes = read(so, buf, sizeof(buf)-1);
                    if (recvbytes > 0) {
                        buf[recvbytes] = '\0';
                        printf ("receive: bytes: %d\n", recvbytes);
                    }
                } while (recvbytes > 0);
                if (recvbytes == 0)
                    n3++;
                t = time(NULL)-t;
                if (t > 0)
                    state = ev;
            }
        }

    }

    printf ("i: %d\n", i);
    printf ("%d %d %d %d timeout state: %d rabish time: %d\n", phash->n, n1, n2, n3, state, rtime);
    hash_close (phash);
    ep_close (ep);
}

int main ()
{
    int t = time(NULL);
    test ();
    printf ("tot time: %d\n", time(NULL)-t);

    perror ("");

    return 0;
}
